package cn.wolfcode.luowowo.interceptor;

import cn.wolfcode.luowowo.cache.service.ISecurityRedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.util.JsonResult;
import cn.wolfcode.luowowo.util.RequestUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 接口防刷拦截器
 */
public class BrushProofInterceptor implements HandlerInterceptor{

    @Autowired
    private ISecurityRedisService securityRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 静态的请求和跨域的请求放行
        if(!(handler instanceof HandlerMethod)){
            return  true;
        }

        //防刷验证          (这个获取的URI是:http://localhost:8080)
        String url = request.getRequestURI().substring(1);// sub1:去掉URI,那获取到的是接口路径
        String ip = RequestUtil.getIPAddress();

        // BRUSH_PROOF:防刷
        String key = RedisKeys.BRUSH_PROOF.join(url, ip);

        if(!securityRedisService.isAllowBrush(key)){
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(JsonResult.error(500, "请勿频繁访问","谢谢咯")));
            return false;
        }

        return true;//程序走到这里需在启动类里配置
    }
}
